package io.sage.common.rxtx;

public class PrivateStringFormat {


	public static String GetDevice(String dev)
	{
		String device = shortTolongNum(toBytes(dev));
		return device;
	}

	public static String shortTolongNum(byte[] dev)
	{
		String longStringNum = "";
		if(dev.length == 0)
		{
			return longStringNum;
		}
		//计算type
		String str_type = Integer.toBinaryString((dev[0] & 0xFF) + 0x100).substring(1);
		String new_strtype = "00"+str_type.substring(0,6);
		String type = ((conver2HexToByte(new_strtype)[0]) & 0xFF)+"";
		if(2 - type.length() != 0)
		{
			type = "0"+type;
		}
		//计算year
		byte byt_year = (byte)(dev[0] & 0x03);
		String str_year = Integer.toBinaryString((byt_year & 0xFF) + 0x100).substring(1);
		String new_stryear = str_year.substring(4,8)+"0000";
		byte byt_year_one = (conver2HexToByte(new_stryear)[0]);

		String str_year_two = Integer.toBinaryString((dev[1] & 0xFF) + 0x100).substring(1);
		String new_stryear_two = "0000"+str_year_two.substring(0,4);
		byte byt_year_two = (conver2HexToByte(new_stryear_two)[0]);

		String year = ((byt_year_one | byt_year_two) +2016)+"";
		//计算month
		String month = ((dev[1] & 0x0F) & 0xFF)+"";
		if(month.length() != 2)
		{
			month = "0"+month;
		}
		//计算num
		String str_num_one = Integer.toBinaryString((dev[2] & 0xFF) + 0x100).substring(1);
		String str_num_two = Integer.toBinaryString((dev[3] & 0xFF) + 0x100).substring(1);
		String str_num = str_num_one + str_num_two;
		String num = Integer.parseInt(str_num,2)+"";
		int bz_length = 5-num.length();
		if(bz_length != 0)
		{
			String str_bz = "";
			for(int i = 0;i<bz_length;i++)
			{
				str_bz += "0";
			}
			num = str_bz +num;
		}
		longStringNum = type + year + month + num;
		//计算整体

		int bz_devlen = 15 - longStringNum.length();
		if(bz_devlen != 0)
		{
			String str_devbz = "";
			for(int i = 0;i<bz_devlen;i++)
			{
				str_devbz += "0";
			}
			longStringNum = longStringNum.substring(0,2)+str_devbz+longStringNum.substring(2,longStringNum.length());
		}

		return longStringNum;
	}

	/**
	 * 二进制字符串转换为byte数组,每个字节以","隔开
	 **/
	public static byte[] conver2HexToByte(String hex2Str) {
		String[] temp = hex2Str.split(",");
		byte[] b = new byte[temp.length];
		for (int i = 0; i < b.length; i++) {
			b[i] = Long.valueOf(temp[i], 2).byteValue();
		}
		return b;
	}


	/**
	 * 将16进制字符串转换为byte[]
	 *
	 * @param str
	 * @return
	 */
	public static byte[] toBytes(String str) {
		if(str == null || str.trim().equals("")) {
			return new byte[0];
		}

		byte[] bytes = new byte[str.length() / 2];
		for(int i = 0; i < str.length() / 2; i++) {
			String subStr = str.substring(i * 2, i * 2 + 2);
			bytes[i] = (byte) Integer.parseInt(subStr, 16);
		}
		return bytes;
	}


}
